﻿using UnityEngine;
using System;
using UnityEngine.UI;
using DG.Tweening;

public class Tip : MonoBehaviour
{
    public RectTransform bg;
    public Text text;

    private float closeTime;
    private Action onClose;

    public static void Show(string content, float duration = 2, Action onClose = null)
    {
        GameObject go = Instantiate(Resources.Load<GameObject>(nameof(Tip)));
        Tip tip = go.GetComponent<Tip>();
        tip.text.text = content;
        tip.bg.localScale = Vector3.zero;
        tip.bg.DOScale(Vector3.one, 0.3f).SetEase(Ease.OutBack);
        tip.closeTime = Time.time + duration;
        tip.onClose = onClose;
    }

    void Update()
    {
        if (closeTime > 0f && closeTime < Time.time)
        {
            closeTime = 0;
            bg.DOScale(Vector3.zero, 0.1f).OnComplete(() =>
            {
                Destroy(gameObject);
                onClose?.Invoke();
            });
        }
    }
}